﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using Microsoft.VisualStudio.TextTemplating;
using Lilium.T4.Hosting;
using System.Web;
using System.Reflection;

namespace Lilium.Web.Mvc.T4
{
    public class T4View : IView
    {
        public T4View(string viewPath)
        {
            if (viewPath == null) throw new ArgumentNullException("viewPath");

            m_ViewPath = viewPath;

            var directiveProcessors = new Dictionary<string, Type>();
            directiveProcessors.Add("PropertyProcessor", typeof(PropertyProcessor));
            directiveProcessors.Add("HttpHeaderProcessor", typeof(HttpHeaderProcessor));

            m_HostOptions = new T4HostOptions(true, true, directiveProcessors, Enumerable.Empty<string>(), new[] { "System" });
        }

        #region IView Members

        public void Render(ViewContext viewContext, TextWriter writer)
        {
            if (viewContext == null) throw new ArgumentNullException("viewContext");
            if (writer == null) throw new ArgumentNullException("writer");

            var templatPath = viewContext.HttpContext.Request.MapPath(ViewPath);
            var engineHost = new Lilium.T4.Hosting.T4EngineHost(templatPath, HostOptions);

            var argumets = new Dictionary<string, object>();
            argumets["Model"] = viewContext.ViewData.Model;
            var result = engineHost.ProcessTemplate(argumets);
            writer.Write(result);
        }

        #endregion

        #region private T4HostOptions HostOptions

        private readonly T4HostOptions m_HostOptions;

        private T4HostOptions HostOptions
        {
            get
            {
                return m_HostOptions;
            }
        }

        #endregion

        #region private string ViewPath

        private readonly string m_ViewPath;

        private string ViewPath
        {
            get
            {
                return m_ViewPath;
            }
        }

        #endregion
    }
}
